package ca.dominion.heritageQuiz.utils {
	
	import ca.dominion.heritageQuiz.globals.Config;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.URLRequest;

	/**
	 * 
	 * @author ghostmonk
	 * 
	 */
	public class ImageLoader extends Sprite {
		
		
		
		private var _loader:Loader;
		private var _callback:Function;
		
		
		
		/**
		 * 
		 * 
		 */
		public function ImageLoader() {
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
			addChild( _loader );
			
		}
		
		
		
		/**
		 * 
		 * @param url
		 * @param callBack
		 * 
		 */
		public function load(url:String, callBack:Function):void {
			
			_loader.unload();
			_callback = callBack;
			_loader.load( new URLRequest( url ) );
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
			
		} 
		
		
		
		private function onComplete( e:Event ):void {
			
			_callback();
			Bitmap( _loader.content ).smoothing = true;
			_loader.contentLoaderInfo.removeEventListener( Event.COMPLETE, onComplete );
			
		}
		
		
		
		private function onIOError(e:IOErrorEvent):void {
			
			_loader.load( new URLRequest( Config.PROJECT_XML.defaultPhoto.@url ) );
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
			
		}
		
		
		
	}
}